/**
 * 上传文件按钮组件（遵循form表单的控件标准, 如果配合antd的form表单则按照表单方式取值/设置值，需要注意的是文件的格式要转换）
 * @param {Function} onChange 选择文件变化时的回调函数
 * @param {?Function} getFileArrFn 可选，获取处理好的文件列表的回调函数
 * @param {Object:} value 文件列表
 * @param {?Number} sliceLength 可选，展示列表中文件名从多长开始显示省略号...
 * @param {?Number} filesCountLimit 可选，上传的文件数量限制
 * @param {?Number} accept 可选，上传的文件类型限制
 * @param {?Number} fileSize 可选，上传的文件大小限制（单位M）
 * @param {?Array} fileTypeList 可选，上传的文件类型 ['jpg','jpeg','gif']
 */

import React, { FC } from 'react';
import { Button, Icon, Toast } from 'antd-mobile-v2';
import styles from './index.less';
// import { DownloadFileByContent, DownloadFileByLink } from '@/utils/index';
import { GetFileUrl, UploadFile } from '@/services/index';
import { FILE_TYPE_LIST, FILES_ACCEPTS } from './constants';
import { Props } from '../form-group';

interface FileProps {
  fileSize?: any;
  fileTypeList?: string[];
  filesCountLimit?: number;
  [propName: string]: any; // 任意类型
}

class FilesUploader extends React.Component<FileProps, any> {
  state = {
    loading: false,
    value: []
  }

  // static getDerivedStateFromProps(nextProps, prevState) {
  //   const { preProps } = prevState;
  //   if (preProps) {
  //     if (preProps?.value?.toString() != nextProps?.value?.toString()) {
  //       return {
  //         value: nextProps.value,
  //         preProps: nextProps
  //       };
  //     }
  //     return { preProps: nextProps };
  //   }
  //   return { value: nextProps.value, preProps: nextProps };
  // }

  resetFiles = () => {
    this.setState({ value: [] });
  }

  handleFileSelect = (e, file) => {
    console.log(e, file);
  }

  handleFileChange = (e) => {
    const filesList = e.target.files;
    // this.customRequest(dataList)
    const dataListArr = [];
    for (const i in filesList) {
      dataListArr.push({
        name: filesList[i].name,
        size: filesList[i].size,
        type: filesList[i].type
      });
    }
    dataListArr.splice(filesList.length, 2);
    this.dealFileFn(dataListArr);
    // if (!this.verify(dataListArr)) {
    //   return
    // }
  }

  // 处理获取满足要求的文件
  dealFileFn = (dataListArr) => {
    const { fileSize = 50, fileTypeList = [...FILE_TYPE_LIST], getFileArrFn } = this.props;
    const arr = dataListArr.filter((item) => {
      const fileName = item.name.match(/\.([0-9,a-z,A-Z]+)$/)?.[1].toLocaleLowerCase();
      return fileTypeList.indexOf(fileName) !== -1 && item.size < fileSize * Math.pow(2, 20) && item.size !== 0;
    });
    getFileArrFn && getFileArrFn(arr);
  }

  // 自定义上传
  customRequest = (file) => {
    file = file.file;
    const type = file.name.match(/\.([0-9,a-z,A-Z]+)$/)?.[1].toLocaleLowerCase();
    if (FILE_TYPE_LIST.indexOf(type) === -1) {
      return Toast.info('附件类型不支持');
    }
    if (file.size > 50 * Math.pow(2, 20)) {
      return Toast.info('附件大小应小于50M');
    }
    if (file.size === 0) {
      return Toast.info('附件不能为空');
    }
    this.sendUploadReq(file);
  }

  checkFilesCount = () => {
    const { filesCountLimit = 8 } = this.props;
    const { value } = this.state;
    return (value?.length || 0) < filesCountLimit;
  }

  sendUploadReq = async (file) => {
    if (!this.checkFilesCount()) return Toast.info('附件数量超过限制');
    this.setState({ loading: true });
    const formData = new FormData();
    formData.append('file', file);
    const res: any = await UploadFile(formData);
    this.setState({ loading: false });

    // form表单直接获取的文件信息格式
    const current = {
      // id: res.id,
      url: res.url,
      name: file.name,
      size: file.size
    };

    this.setState((prevState) => ({
      value: [current].concat(prevState.value ? prevState.value : [])
    }), () => this.props.onChange && this.props.onChange(this.state.value, current));
  }

  handleFilesDownload = (file) => {
    // const url = file.url || file.uri;
    // if (url) {
    //   DownloadFileByLink(url, file.name);
    // } else {
    //   DownloadFileByContent(file);
    // }
  }

  handleFilesDelete = (index) => {
    let deleteFile = undefined;
    this.setState((prevState) => {
      const list = [...prevState.value];
      deleteFile = list.splice(index, 1);
      return {
        value: list
      };
    }, () => this.props.onChange && this.props.onChange(this.state.value, deleteFile));
  }

  render() {
    // 文件类型限制
    // const accept = FILES_ACCEPTS.join(',');
    const { value, loading } = this.state;
    const { sliceLength = 15, accept } = this.props;
    const getFileSizeString = (size) => {
      if (!size) return '';
      if (size > 800 * Math.pow(2, 10)) {
        return `（${Math.floor(size / Math.pow(2, 20) * 100) / 100}Mb）`;
      }
      return `（${Math.floor(size / Math.pow(2, 10) * 100) / 100}Kb）`;
    };
    const transName = (name) => {
      if (name.length > sliceLength) {
        return `${name.slice(0, sliceLength)}...`;
      }
      return name;
    };
    return (
      <div>
        <input
          multiple
          type="file"
          accept={accept}
          name="上传文件"
          onChange={this.handleFileChange}
        // onInput={this.handleFileSelect}
        />
        {/* <Button className={styles.uploadFilesButton} loading={loading}><i className="iconfont icon-upload"></i>上传文件</Button> */}
        <div className={styles.filesReadme}></div>
        <div className={styles.filesList}>
          {
            value?.map((item, index) => {
              if (item) {
                return (
                  <span key={index} className={styles.filesListItem} >
                    <span style={{ cursor: 'pointer' }} onClick={() => this.handleFilesDownload(item)}>
                      <Icon type="paper-clip" style={{ color: '#999', margin: '0 8px' }} />
                      {transName(item.name)} {getFileSizeString(item.size)}
                    </span>
                    <i
                      className="iconfont icon-shanchu"
                      style={{ color: '#999', cursor: 'pointer' }}
                      onClick={() => this.handleFilesDelete(index)}
                    >
                    </i>
                  </span>
                );
              }
            })
          }
        </div>
      </div>
    );
  }
}

export default FilesUploader;
